import config from "@/config/index.js"

class Ws {
	constructor() {
		this.ws = null
		this._connected = false
		this._reconnectTimer = null
		this._heartbeatTimer = null
		this._baseUrl = ''
		this._callbacks = {} // 消息路由表 { key: function }
		this._userId = ''
	}

	/* 1. 建立连接 --------------------------------------------------*/
	connect(userId) {
		if (this._connected) return Promise.resolve()
		this._baseUrl = config.WS_URL
		this._userId = userId
		return new Promise((resolve, reject) => {
			this.ws = uni.connectSocket({
				url: this._baseUrl + `?userId=${userId}`,
				header: {
					'content-type': 'application/json'
				},
				complete: () => {
					
				}
			})

			this.ws.onOpen(() => {
				console.log(8888888)
				resolve()
				this._connected = true
				this._resetHeartbeat()
			})

			this.ws.onMessage((e) => {
				console.log('3333333331',e)
				// 统一把 e.data 拿出来
				const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data
				// 简单路由：每条消息带 {type: "xxx", payload: {...}}
				if (data.type && this._callbacks[data.type]) {
					this._callbacks[data.type](data)
				} 
				console.log(data,"pppppp")
			})
			this.ws.onClose(() => {
				console.log(22,'关闭成功')
				this._connected = false
				this._reconnect()
			})

			this.ws.onError((err) => {
				this._connected = false
				reject(err)
				this._reconnect()
			})
		})
	}

	/* 2. 发送消息 --------------------------------------------------*/
	send(msg) {
		if (!this._connected) return uni.showToast({
			title: 'WebSocket 未连接',
			icon: 'none'
		})
		const str = typeof msg === 'string' ? msg : JSON.stringify(msg)
		this.ws.send({
			data: str
		})
	}

	/* 3. 注册消息监听 ----------------------------------------------*/
	on(type, cb) {
		this._callbacks[type] = cb
	}
	off(type) {
		delete this._callbacks[type]
	}

	/* 4. 主动关闭 --------------------------------------------------*/
	close() {
		if (this.ws) {
			this._connected = false
			this._clearTimers()
			this.ws.close({})
			console.log(11111)
		}
	}

	/* 5. 心跳包 ----------------------------------------------------*/
	_resetHeartbeat() {
		this._clearTimers()
		this._heartbeatTimer = setInterval(() => {
			this.send({
				type: 'ping'
			})
		}, 30000)
	}
	_clearTimers() {
		clearInterval(this._heartbeatTimer)
		clearTimeout(this._reconnectTimer)
	}
	_reconnect() {
		if (this._connected) return
		this._clearTimers()
		this._reconnectTimer = setTimeout(() => {
			// this.connect(this._userId)
		}, 3000)
	}
}

// 单例导出
const ws = new Ws()
export default ws